import os
import sys
import shutil

GO_BUILD_CMD = "go build -o {cc} {f}"


BIN_LIST = ["watcher", "inithook", "testbuild", "wordbrush", "excel2json"]


def build_hook(projname, gof, outpath):
    if projname == "watcher":
        print("run hook watcher...")
        gopath = os.path.dirname(gof)
        path_hook = os.path.join(gopath, "hook")
        opath_hook = os.path.join(outpath, "hook")
        if os.path.isdir(opath_hook):
            shutil.rmtree(opath_hook)
        shutil.copytree(path_hook, opath_hook)

        path_config = os.path.join(gopath, "config.json")
        opath_config = os.path.join(outpath, "config.json")
        if os.path.isfile(opath_config):
            os.remove(opath_config)
        shutil.copy(path_config, opath_config)


def go_build(outpath, projname, gfname="main.go"):
    print("go build ", projname)
    
    out_path = os.path.abspath(outpath)
    out_f = os.path.join(out_path, projname)

    bpath = os.getcwd()
    os.chdir(os.path.join(bpath, projname))
    go_f = os.path.join(bpath, projname, gfname)
    cmd = GO_BUILD_CMD.format(cc=out_f, f=go_f)
    build_hook(projname, go_f, out_path)
    return os.system(cmd)


if __name__ == "__main__":
    rootpath = os.path.dirname(os.getcwd())
    distpath = os.path.join(rootpath, "dist")
    if len(sys.argv) > 1:
        if not sys.argv[1] in BIN_LIST:
            print("%s not found the tool proj in BIN_LIST!")
        go_build(distpath, sys.argv[1])
    else:
        for key in BIN_LIST:
            go_build(distpath, key)
